package com.xhwl.centiotdata.suppliersystem.vehicle.FuShi;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.dto.dahua.VehicleInOutRecordDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.fushi.VehicleInOutRecordFuShiDTO;
import com.xhwl.centiotdata.pojo.dto.fushi.VehiclePayRecordFuShiDTO;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.cent.vehicle.bo.config.VehicleIntegrationConfigBO;
import com.xhwl.common.pojo.cent.vehicle.bo.http.query.QueryAccessRecordBO;
import com.xhwl.common.utils.ChkUtil;
import com.xhwl.common.utils.HttpUtils;
import com.xhwl.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 车行对接富士的实现逻辑类，即处理程序
 */
@Slf4j
@Component
public class FuShiHandler {

    /**
     * 获取记录
     * @param vehicleIntegrationConfigBO
     * @return
     */
    public List<VehiclePayRecordFuShiDTO> pullPayRecord(VehicleIntegrationConfigBO vehicleIntegrationConfigBO, QueryAccessRecordBO queryAccessRecordBO){

        List<VehiclePayRecordFuShiDTO> vehiclePayRecordFuShiDTOS = new LinkedList<>();
        Integer pageNum = 1;
        List<VehiclePayRecordFuShiDTO> recordList = null;
        do {
            recordList = this.getPayRecord(vehicleIntegrationConfigBO,pageNum, queryAccessRecordBO);
            if (CollectionUtils.isEmpty(recordList)) {
                break;
            }
            vehiclePayRecordFuShiDTOS.addAll(recordList);
            ++pageNum;
        }while (!CollectionUtils.isEmpty(recordList) && recordList.size() == 500);

        return vehiclePayRecordFuShiDTOS;
    }

    private List<VehiclePayRecordFuShiDTO> getPayRecord(VehicleIntegrationConfigBO vehicleIntegrationConfigBO, int pageNum, QueryAccessRecordBO queryAccessRecordBO){
        String host = vehicleIntegrationConfigBO.getVehicleParkingInfoBO().getHost();
        checkSupplierConfigDTO(vehicleIntegrationConfigBO);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("PageSize", "500");
        paramMap.put("CurrentPage", String.valueOf(pageNum));
        paramMap.put("OrderBy", "id");
        paramMap.put("OrderType", "true");
        paramMap.put("where", String.format("TollTime>='%S' AND TollTime<'%S'", date2Str(queryAccessRecordBO.getStartTime(), "yyyy-MM-dd HH:mm:ss"), date2Str(queryAccessRecordBO.getEndTime(), "yyyy-MM-dd HH:mm:ss")));
        String json = JSON.toJSONString(paramMap);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json");
        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpUtils.doPost(host, "/TollRecord/getbycustom", headerMap, paramMap, json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonResult = new JSONObject();
        if(200 == httpResponse.getStatusLine().getStatusCode()) {
            String str = "";
            try {
                str = EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
            jsonResult = JSON.parseObject(str);
        }

        JSONArray jsonArray = jsonResult.getJSONArray("Records");
        String records = "";
        if(ChkUtil.isNull(jsonArray)) {
            return new ArrayList<>();
        }
        records = jsonArray.toJSONString();
        return JSONObject.parseArray(records,VehiclePayRecordFuShiDTO.class);
    }


    /**
     * 获取记录
     * @param vehicleIntegrationConfigBO
     * @return
     */
    public List<VehicleInOutRecordFuShiDTO> pullInRecord(VehicleIntegrationConfigBO vehicleIntegrationConfigBO, QueryAccessRecordBO queryAccessRecordBO){

        List<VehicleInOutRecordFuShiDTO> vehicleInOutRecordFuShiDTOS = new LinkedList<>();
        Integer pageNum = 1;
        List<VehicleInOutRecordFuShiDTO> recordList = null;
        do {
            recordList = this.getInRecord(vehicleIntegrationConfigBO,pageNum, queryAccessRecordBO);
            if (CollectionUtils.isEmpty(recordList)) {
                break;
            }
            vehicleInOutRecordFuShiDTOS.addAll(recordList);
            ++pageNum;
        }while (!CollectionUtils.isEmpty(recordList) && recordList.size() == 500);

        return vehicleInOutRecordFuShiDTOS;
    }

    private List<VehicleInOutRecordFuShiDTO> getInRecord(VehicleIntegrationConfigBO vehicleIntegrationConfigBO, Integer pageNum, QueryAccessRecordBO queryAccessRecordBO){
        String host = vehicleIntegrationConfigBO.getVehicleParkingInfoBO().getHost();
        checkSupplierConfigDTO(vehicleIntegrationConfigBO);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("PageSize", "500");
        paramMap.put("CurrentPage", String.valueOf(pageNum));
        paramMap.put("OrderBy", "id");
        paramMap.put("OrderType", "true");
        paramMap.put("where", String.format("InTime>='%S' AND InTime<'%S'", date2Str(queryAccessRecordBO.getStartTime(), "yyyy-MM-dd HH:mm:ss"), date2Str(queryAccessRecordBO.getEndTime(), "yyyy-MM-dd HH:mm:ss")));
        String json = JSON.toJSONString(paramMap);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json");
        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpUtils.doPost(host, "/InVehicleRecord/GetByCustom", headerMap, paramMap, json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonResult = new JSONObject();
        if(200 == httpResponse.getStatusLine().getStatusCode()) {
            String str = "";
            try {
                str = EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
            jsonResult = JSON.parseObject(str);
        }

        JSONArray jsonArray = jsonResult.getJSONArray("Records");
        String records = "";
        if(ChkUtil.isNull(jsonArray)) {
            return new ArrayList<>();
        }
        records = jsonArray.toJSONString();
        return JSONObject.parseArray(records,VehicleInOutRecordFuShiDTO.class);
    }

    /**
     * 获取记录
     * @param vehicleIntegrationConfigBO
     * @return
     */
    public List<VehicleInOutRecordFuShiDTO> pullOutRecord(VehicleIntegrationConfigBO vehicleIntegrationConfigBO, QueryAccessRecordBO queryAccessRecordBO){
        List<VehicleInOutRecordFuShiDTO> vehicleInOutRecordFuShiDTOS = new LinkedList<>();
        Integer pageNum = 1;
        List<VehicleInOutRecordFuShiDTO> recordList = null;
        do {
            recordList = this.getOutRecord(vehicleIntegrationConfigBO,pageNum, queryAccessRecordBO);
            if (CollectionUtils.isEmpty(recordList)) {
                break;
            }
            vehicleInOutRecordFuShiDTOS.addAll(recordList);
            ++pageNum;
        }while (!CollectionUtils.isEmpty(recordList) && recordList.size() == 500);

        return vehicleInOutRecordFuShiDTOS;

    }

    private List<VehicleInOutRecordFuShiDTO> getOutRecord(VehicleIntegrationConfigBO vehicleIntegrationConfigBO, Integer pageNum, QueryAccessRecordBO queryAccessRecordBO){
        String host = vehicleIntegrationConfigBO.getVehicleParkingInfoBO().getHost();
        checkSupplierConfigDTO(vehicleIntegrationConfigBO);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("PageSize", "500");
        paramMap.put("CurrentPage", String.valueOf(pageNum));
        paramMap.put("OrderBy", "id");
        paramMap.put("OrderType", "true");
        paramMap.put("where", String.format("OutTime>='%S' AND OutTime<'%S'", date2Str(queryAccessRecordBO.getStartTime(), "yyyy-MM-dd HH:mm:ss"), date2Str(queryAccessRecordBO.getEndTime(), "yyyy-MM-dd HH:mm:ss")));
        String json = JSON.toJSONString(paramMap);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json");
        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpUtils.doPost(host, "/OutVehicle/GetByCustom", headerMap, paramMap, json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonResult = new JSONObject();
        if(200 == httpResponse.getStatusLine().getStatusCode()) {
            String str = "";
            try {
                str = EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
            jsonResult = JSON.parseObject(str);
        }

        JSONArray jsonArray = jsonResult.getJSONArray("Records");
        String records = "";
        if(ChkUtil.isNull(jsonArray)) {
            return new ArrayList<>();
        }
        records = jsonArray.toJSONString();
        return JSONObject.parseArray(records,VehicleInOutRecordFuShiDTO.class);
    }


    private void checkSupplierConfigDTO(VehicleIntegrationConfigBO vehicleIntegratedConfigBO) {
        if (vehicleIntegratedConfigBO == null || vehicleIntegratedConfigBO.getVehicleParkingInfoBO() == null) {
            throw new BusinessException("配置信息无vehicleIntegratedConfigBO");
        }
        if (StringUtils.isBlank(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost())) {
            throw new BusinessException("配置信息无host,请到供应商配置平台配置");
        }
    }

    public static String date2Str(Date date, String format) {
        String result = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (date != null) {
            result = sdf.format(date);
        }
        return result;
    }
}

